using System.Reflection;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;

namespace UserMgr.WebAPI;

public class UnitOfWorkFilter:IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var result = await next();
        if (result.Exception!=null)//只有成功才会savechange
        {
            return;
        }

        var actionDesc = context.ActionDescriptor as ControllerActionDescriptor;
        if (actionDesc==null)
        {
            return;
        }

        var unitOfWorkAttribute = actionDesc.MethodInfo.GetCustomAttribute<UnitOfWorkAttribute>();
        if (unitOfWorkAttribute==null)
        {
            return;
        }
        
        foreach (var dbContextType in unitOfWorkAttribute.DbContextTypes)
        {
            //获取dbcontext实例
            var dbCtx = context.HttpContext.RequestServices.GetService(dbContextType) as DbContext;
            if (dbCtx!=null)
            {
                await dbCtx.SaveChangesAsync();
            }
        }
    }
}